package edu.ynu.MyProject.shiro;

import edu.ynu.MyProject.dao.IUserDAO;
import edu.ynu.MyProject.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class JpaRealm extends AuthorizingRealm {

    @Autowired
    private IUserDAO iUserDao;
    /**
     * 认证逻辑：验证用户的用户名和密码。
     *
     * @param token 登录时传入的用户名和密码
     * @return 认证信息
     * @throws AuthenticationException 认证失败时抛出异常
     */
    /**
     * 认证逻辑：验证用户的用户名和 MD5 加密密码。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();

        // 从数据库中查找用户
        Optional<User> optionalUser = iUserDao.findByUsername(username);
        if (!optionalUser.isPresent()) {
            throw new UnknownAccountException("用户不存在");
        }
        User user = optionalUser.get();
        // 返回认证信息，Shiro 自动加密匹配
        return new SimpleAuthenticationInfo(username, user.getPassword(), getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
